/**
 * 
 */
package org.swing.utility.jai.info;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.MetadataException;
import com.drew.metadata.Tag;
import com.drew.metadata.exif.ExifDirectory;

/**
 * @author Quynh Nhu
 * 
 */
public class JHeadUtil {
	public static String getComment(File imageFile) {
		try {
			Metadata metadata = ImageMetadataReader.readMetadata(imageFile);
			Directory directory = metadata.getDirectory(ExifDirectory.class);
			return directory.getString(ExifDirectory.TAG_IMAGE_DESCRIPTION);
		} catch (ImageProcessingException e) {
			return null;
		}

	}

	public static Map<String, String> getMetaData(File imageFile) {
		try {
			Map<String, String> keywords = new LinkedHashMap<String, String>();
			Metadata metadata = ImageMetadataReader.readMetadata(imageFile);
			Iterator<Directory> directories = metadata.getDirectoryIterator();
			while (directories.hasNext()) {
				Directory directory = (Directory) directories.next();
				Iterator<Tag> tags = directory.getTagIterator();
				while (tags.hasNext()) {
					Tag tag = tags.next();
					keywords.put(tag.getTagName(), tag.getDescription());
				}
			}
			return keywords;
		} catch (ImageProcessingException e) {
			return Collections.emptyMap();
		} catch (MetadataException e) {
			// TODO Auto-generated catch block
			return Collections.emptyMap();
		}
	}

	public static void setComment(File imageFile, String comment) {
		exec(new String[] { "jhead", "-cl", comment,
				imageFile.getAbsolutePath() });
	}

	private static boolean exec(final String[] command) {
		Process proc;

		try {
			proc = Runtime.getRuntime().exec(command);
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}

		int exitStatus;

		while (true) {
			try {
				exitStatus = proc.waitFor();
				break;
			} catch (java.lang.InterruptedException e) {
			}
		}
		if (exitStatus != 0) {
			System.err.println("Error executing command: " + exitStatus);
		}
		return (exitStatus == 0);
	}

}
